package com.yc.demo.d0304;

import javax.servlet.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * 设置字符集编码
 * value 表示过滤的资源路径
 *   /* 中的 * 表示0~n个字符 => 匹配多个地址
 */

@WebFilter(filterName = "EncodingFilter", value = "/*")
public class EncodingFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println(" EncodingFilter 初始化");
    }

    public void destroy() {
        System.out.println(" EncodingFilter 销毁");
    }

    // HttpServletRequest req, HttpServletResponse resp
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws ServletException, IOException {
        // 字符集要尽早的设置
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // 默认设置资源返回结果类型是 json
        // response.setContentType("application/json;charset=utf-8");

        // 执行后续过滤器方法。如果没有后续过滤，那么请求将会送达目标资源
        chain.doFilter(request, response);
        // 请求到达目标资源后，响应过程会执行过滤器链后面的代码
        System.out.println(" EncodingFilter 执行过滤（后）");
    }
}
